<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserslist()">
                        <el-button slot="append" icon="el-icon-search" @click="getUserslist()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible">添加用户</el-button>
                </el-col>
            </el-row >
            <el-table :data="userslist" border stripe style="width: 100%">
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                         <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                             <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialogVisible(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户 -->
        <el-dialog title="添加用户" :visible.sync="addFormVisible" width="50%" @close="handleClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addRuleForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input type="text" v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input type="text" v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog title="修改用户" :visible.sync="editFormVisible" width="50%" @close="editClose">
            <el-form :model="editForm" :rules="editFormRules" ref="editRuleForm" label-width="80px">
                <el-form-item label="用户名">
                    <el-input type="text" v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input type="text" v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </div>
        </el-dialog>
         <!-- 分配角色 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisble" width="50%" @close="rolesClose">
            <div>
                <p>当前的用户: {{roleInfo.username}}</p>
                <p>当前的角色: {{roleInfo.role_name}}</p>
                <p>分配新角色:
                    <el-select v-model="selectSetId" placeholder="请选择">
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisble = false">取 消</el-button>
                <el-button type="primary" @click="setRoles">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
            var validateEmail = (rule, value, callback) => {
	        if (value === '') {
	          callback(new Error('请正确填写邮箱'));
	        } else {
	          if (value !== '') { 
	            var reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
	            if(!reg.test(value)){
	              callback(new Error('请输入有效的邮箱'));
	            }
	          }
	          callback();
	        }
	      };
            var validateMobilePhone = (rule, value, callback) => {
	        if (value === '') {
	          callback(new Error('手机号不可为空'));
	        } else {
	          if (value !== '') { 
	            var reg=/^1[3456789]\d{9}$/;
	            if(!reg.test(value)){
	              callback(new Error('请输入有效的手机号码'));
	            }
	          }
	          callback();
	        }
	      }
        return {
            userslist:[],
            queryInfo:{
                query:'',
                // 当前的页数
                pagenum:1,
                pagesize:2
            },
            total:0,
            pagenum:[],
            addFormVisible:false,
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addFormRules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    {required: true,message: '请输入密码', trigger: 'blur'},
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email:[
                    {required: true,message: '请输入邮箱', trigger: 'blur'},{validator: validateEmail, trigger: 'blur'}
                    ],
                mobile:[
                    {required: true,message: '请输入手机号', trigger: 'blur'},{validator: validateMobilePhone, trigger: 'blur'}
                    ]
            },
            editFormVisible:false,
            editForm:{},
            editFormRules:{
                email:[
                    {required: true,message: '请输入邮箱', trigger: 'blur'},{validator: validateEmail, trigger: 'blur'}
                    ],
                mobile:[
                    {required: true,message: '请输入手机号', trigger: 'blur'},{validator: validateMobilePhone, trigger: 'blur'}
                    ]
            },
            // 分配角色
            setRightDialogVisble:false,
            roleInfo:{},
            rolesList:[],
            selectSetId:''
        }
    },
    created() {
        this.getUserslist()
    },
    methods: {
        async getUserslist(){
            const {data:res} = await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status !== 200){
                return this.$message.error('数据获取失败')
            }
            this.userslist = res.data.users
            this.total = res.data.total
        },
        handleSizeChange(val) {
            this. queryInfo.pagesize = val
            this.getUserslist()
        },
        handleCurrentChange(val) {
            this. queryInfo.pagenum = val
            this.getUserslist()
        },
       async userStateChange(val){
          const {data:res}= await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
          if (res.meta.status !== 200) {
              return this.$message.error('更改失败');
          }
          this.$message({
          message: '更改成功',
          type: 'success'
         });
        },
        addDialogVisible(){
            this.addFormVisible = true
        },
        handleClose(){
            this.$refs.addRuleForm.resetFields()
        },
        addUser(){
            this.$refs.addRuleForm.validate(async valid => {
                const {data:res} = await this.$http.post('users',this.addForm)
                if(res.meta.status !== 201){
                    return this.$message.error('添加失败')
                }
                this.$message({
                    message: '添加用户成功',
                    type: 'success'
                });
                this.getUserslist()
            })
        },
        async editDialogVisible(id){
            const {data:res} = await this.$http.get('users/' + id)
            this.editForm = res.data
            this.editFormVisible = true
        },
        editClose(){
            this.$refs.editRuleForm.resetFields()
        },
        editUser(){
            this.$refs.editRuleForm.validate(async valid => {
                if(!valid) return
                const {data:res} = await this.$http.put('users/' + this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile})
                if(res.meta.status !== 200){
                    return this.$message.error('修改失败')
                }
                this.editFormVisible = false
                this.getUserslist()
                this.$message({
                    message: '修改用户成功',
                    type: 'success'
                }); 
            })
        },
        deleteUserById(id){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async() => {
            await this.$http.delete('users/' + id)
            this.getUserslist()
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
        },
        // 分配角色
        async showSetRightDialog(roleinfo){
            this.roleInfo = roleinfo
            const {data:res} = await this.$http.get('roles')
            this.rolesList = res.data
            this.setRightDialogVisble = true
        },
        async setRoles(){
            if(!this.selectSetId){
                return this.$message.error('请选择分配的角色')
            }
            const {data:res} = await this.$http.put(`users/${this.roleInfo.id}/role`,{rid:this.selectSetId})
            if (res.meta.status !== 200) {
                 return this.$message.error('更新失败！')
            }
            this.getUserslist()
            this.setRightDialogVisble = false
            this.$message({
                type: 'success',
                message: '更改成功!'
            });
        },
        rolesClose(){
            this.selectSetId = '',
            this.roleInfo = {}
        }
    },

}
</script>

<style lang="less" scoped>

</style>